package com.openbravo.data.loader.dialect;


import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.DBSession;
import e.odbo.DB;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractDataBase<T extends AbstractDataBase> {
    protected String host="localhost";
    protected int port=3306;
    protected String database="test";
    protected String user="root";
    protected String password="";

    protected String jdbcType;

    protected Map<String,String> connectProp=new HashMap<>();

    public AbstractDataBase(String jdbcType){
        this.jdbcType=jdbcType;
    }

    public T setProperty(String property,String value){
        this.connectProp.put(property,value);
        return (T) this;
    };

    public T host(String host){
        this.host=host;
        return (T) this;
    }

    public T port(int port){
        this.port=port;
        return (T)this;
    }

    public  T database(String database){
        this.database=database;
        return (T)this;
    }

    public T user(String user,String password){
        this.user=user;
        this.password=password;
        return (T)this;
    }

    public DB connect()throws BasicException{
        DBSession dbSession=new DBSession(buildUrl(),user,password);
        return DB.getInstance(dbSession);
    }


    public String buildUrl(){
        String prop="";
        String[] keys=(String[])connectProp.keySet().toArray();
        for(int i=0;i<connectProp.size();i++) {
            if(i>0)
                prop="&"+prop;
            prop += keys[i] + connectProp.get(keys[i]);
        }
        if(!prop.isEmpty())
            prop="?"+prop;
        return String.format("jdbc:%s://%s:%d/%s%s",jdbcType, host, port, database, prop);
    }


}
